package com.lzw.DailyAudit.service.dateAggregation_02.DailyAudit.service.dealSourceData_01;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hooya.fa.eu.biz.DailyAudit.entity.DailyAuditStatus;
import com.hooya.fa.eu.biz.DailyAudit.entity.TempKcjlDailyHy;
import com.hooya.fa.eu.biz.DailyAudit.entity.dto.TempKcjlDailyHyDTO;
import com.hooya.fa.eu.biz.DailyAudit.mapper.*;
import com.hooya.fa.eu.biz.DailyAudit.service.dateAggregation_02.CommonService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Data
@Slf4j
@Service
public class KcjlHy {

    @Autowired
    private DailyTempJcjlMapper tempJcjlMapper;

    @Autowired
    private DailyTempPkpyMapper tempPkpyMapper;

    @Autowired
    private DailyTempThjlMapper tempThjlMapper;

    @Autowired
    private DailyTempXsjlMapper tempXsjlMapper;

    @Autowired
    private DailyTempZyjlMapper tempZyjlMapper;

    @Autowired
    private DailyTempKcjlDailyHyMapper tempKcjlDailyHyMapper;

    @Autowired
    private DailyTempKcjlDailyMapper tempKcjlDailyMapper;

    @Autowired
    private DailyJcjlHistoryMapper jcjlHistoryMapper;

	@Autowired
	private DailyAuditStatusMapper statusMapper;

	@Autowired
	private CommonService commonService;

    private final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    private final Map<String, String> ckCountryDict = new HashMap<>();
    private final Map<String, String> ABNORMAL_BELONGS = new HashMap<String, String>() {{
        put("HY-SCBXS22114494", "FDS-DE");
        put("HY-SCBXS21106017", "COSTWAY-PL");
        put("HY-SCBXS20044489", "FDS-DE");
        put("FRLT-220002NB", "COSTWAY-FR");
    }};
    private final Map<String, String> VIRTUAL_CK = new HashMap<>();
    private final Map<String, String> RESTOCK_PLACE_LIST = new HashMap<>();

    {
        // 初始化一些必要的配置
        ckCountryDict.put("EU01", "DE");
        ckCountryDict.put("EU02", "DE");
        ckCountryDict.put("EU99", "DE");
        ckCountryDict.put("EU98", "DE");
        ckCountryDict.put("EU97", "DE");
        ckCountryDict.put("EU96", "DE");
        ckCountryDict.put("EU生资库", "DE");
        ckCountryDict.put("EU03", "DE");
        ckCountryDict.put("EU04", "FR");
        ckCountryDict.put("EU95", "FR");
        ckCountryDict.put("EU94", "FR");
        ckCountryDict.put("EU05", "DE");
        ckCountryDict.put("EU06", "IT");
        ckCountryDict.put("EU07", "PL");
        ckCountryDict.put("EU93", "DE");
        ckCountryDict.put("EU92", "DE");
        ckCountryDict.put("EU91", "PL");
        ckCountryDict.put("EU90", "PL");
        ckCountryDict.put("EU89", "FR");
        ckCountryDict.put("EU88", "IT");
        ckCountryDict.put("EU87", "IT");
        ckCountryDict.put("EU86", "FR");
        ckCountryDict.put("EU08", "PL");
        ckCountryDict.put("EU10", "FR");
        ckCountryDict.put("EU09", "PL");
        ckCountryDict.put("EU101", "FR");
        ckCountryDict.put("EU71", "PL");
        ckCountryDict.put("EU70", "PL");
        ckCountryDict.put("EU85", "FR");
        ckCountryDict.put("EU79", "DE");
        ckCountryDict.put("EU78", "DE");
        ckCountryDict.put("EU11", "PL");
        ckCountryDict.put("EU72", "FR");
        ckCountryDict.put("EU100", "PL");
        ckCountryDict.put("EU102", "FR");
        ckCountryDict.put("EU103", "DE");
        ckCountryDict.put("EU104", "IT");
        ckCountryDict.put("EU105", "FR");
        ckCountryDict.put("EU73", "PL");
        ckCountryDict.put("EU201", "DE");
        ckCountryDict.put("EU202", "FR");
        ckCountryDict.put("EU203", "PL");
        ckCountryDict.put("EU204", "FR");
        ckCountryDict.put("EU205", "DE");
        ckCountryDict.put("EU206", "IT");
        ckCountryDict.put("EU207", "PL");
        ckCountryDict.put("EU208", "PL");
        ckCountryDict.put("EU209", "PL");
        ckCountryDict.put("EU106", "PL");
        ckCountryDict.put("EU107", "PL");
        ckCountryDict.put("EU108", "PL");
        ckCountryDict.put("EU84", "DE");
        ckCountryDict.put("EU109", "DE");
        ckCountryDict.put("EU110", "DE");
        ckCountryDict.put("EU112", "PL");
        ckCountryDict.put("EU111", "PL");
        ckCountryDict.put("EU114", "FR");
        ckCountryDict.put("EU120", "DE");
        ckCountryDict.put("EU113", "DE");
        ckCountryDict.put("EU83", "FR");
        ckCountryDict.put("EU115", "DE");
        ckCountryDict.put("EU116", "IT");
        ckCountryDict.put("EU117", "DE");
        ckCountryDict.put("EU80", "IT");
        ckCountryDict.put("EU118", "IT");
        ckCountryDict.put("EU81", "IT");
        ckCountryDict.put("EU82", "IT");
        ckCountryDict.put("EU119", "PL");
        ckCountryDict.put("EU121", "PL");
        ckCountryDict.put("EU122", "FR");
        ckCountryDict.put("EU123", "PL");
        ckCountryDict.put("EU124", "PL");
        ckCountryDict.put("EU125", "PL");
        ckCountryDict.put("EU15", "DE");
        ckCountryDict.put("EU12", "IT");
        ckCountryDict.put("EU134", "IT");
        ckCountryDict.put("EU136", "DE");

        // 初始化VIRTUAL_CK映射表
        VIRTUAL_CK.put("EU100", "EU09");
        VIRTUAL_CK.put("EU102", "EU10");
        VIRTUAL_CK.put("EU103", "EU05");
        VIRTUAL_CK.put("EU104", "EU06");
        VIRTUAL_CK.put("EU105", "EU10");
        VIRTUAL_CK.put("EU106", "EU09");
        VIRTUAL_CK.put("EU107", "EU11");
        VIRTUAL_CK.put("EU108", "EU07");
        VIRTUAL_CK.put("EU109", "EU01");
        VIRTUAL_CK.put("EU110", "EU05");
        VIRTUAL_CK.put("EU112", "EU07");
        VIRTUAL_CK.put("EU111", "EU11");
        VIRTUAL_CK.put("EU114", "EU10");
        VIRTUAL_CK.put("EU120", "EU05");
        VIRTUAL_CK.put("EU117", "EU01");
        VIRTUAL_CK.put("EU118", "EU06");
        VIRTUAL_CK.put("EU119", "EU09");
        VIRTUAL_CK.put("EU121", "EU11");
        VIRTUAL_CK.put("EU123", "EU07");
        VIRTUAL_CK.put("EU124", "EU09");
        VIRTUAL_CK.put("EU125", "EU11");

        // 初始化RESTOCK_PLACE_LIST映射表
        RESTOCK_PLACE_LIST.put("EU97", "EU01");
        RESTOCK_PLACE_LIST.put("EU96", "EU01");
        RESTOCK_PLACE_LIST.put("EU95", "EU04");
        RESTOCK_PLACE_LIST.put("EU94", "EU04");
        RESTOCK_PLACE_LIST.put("EU93", "EU05");
        RESTOCK_PLACE_LIST.put("EU92", "EU05");
        RESTOCK_PLACE_LIST.put("EU91", "EU07");
        RESTOCK_PLACE_LIST.put("EU90", "EU07");
        RESTOCK_PLACE_LIST.put("EU88", "EU06");
        RESTOCK_PLACE_LIST.put("EU87", "EU06");
        RESTOCK_PLACE_LIST.put("EU101", "EU10");
        RESTOCK_PLACE_LIST.put("EU71", "EU09");
        RESTOCK_PLACE_LIST.put("EU70", "EU09");
        RESTOCK_PLACE_LIST.put("EU72", "EU10");
    }


    // 主要处理逻辑--生成Tempkcjl_dality_hy数据
    public void KcjlHy(String currentDate) {
        try {
			String name = "KcjlHy-01";
			DailyAuditStatus dailyAuditStatus = statusMapper.selectStatus(name, currentDate);
			if(dailyAuditStatus != null && dailyAuditStatus.getFlag() == 1){
				log.info("{} - 该方法已执行，进行跳过！",name);
				return;
			}
			log.info("开始执行KcjlHy");

            // 获取前一天
            LocalDate current = LocalDate.parse(currentDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")); // 2025-08-01
            String hydate = current.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // 2025-07-31(2025-08-01的前一天)

            // 获取进仓历史记录
            List<TempKcjlDailyHyDTO> jcjlhis = getJcjlHis();
            // 获取最后的进仓历史记录
            List<TempKcjlDailyHyDTO> jcjl_last = getLastJcjlhis(jcjlhis, currentDate);
            // 进仓记录
            List<TempKcjlDailyHyDTO> jcjldata = tempJcjlMapper.getJcjlData(currentDate);
            // 盘亏盘盈
            List<TempKcjlDailyHyDTO> pkpydata = tempPkpyMapper.getPkpyData(currentDate);
            // 退货记录
            List<TempKcjlDailyHyDTO> thjldata = tempThjlMapper.getThjlData(currentDate).stream().map(this::alterbelongs).collect(Collectors.toList());
            // 销售记录
            List<TempKcjlDailyHyDTO> xsjldata = tempXsjlMapper.getXsjlData(currentDate).stream().map(this::alterbelongs).collect(Collectors.toList());
            // 转运记录
            List<TempKcjlDailyHyDTO> zyjldata = tempZyjlMapper.getZyjlData(currentDate);
            // 初始库存货源
            List<TempKcjlDailyHyDTO> kcjl_hy = tempKcjlDailyHyMapper.getHyData(hydate);


            // 聚合相同记录
            thjldata = aggregateRecords(thjldata);
            // 聚合相同记录
            xsjldata = aggregateRecords(xsjldata);
            // 处理数据 -- 日期
            log.info("处理日期: {}", currentDate);


            // 处理数据
            kcjl_hy = getFinalData(
                    jcjldata,
                    pkpydata,
                    thjldata,
                    xsjldata,
                    zyjldata,
                    jcjl_last,
                    kcjl_hy
            );

			// 过滤掉sl为0的记录并设置日期
			kcjl_hy = kcjl_hy.stream()
					.filter(r -> r.getSl() != 0)
					.peek(record -> record.setDate(currentDate))
					.collect(Collectors.toList());

            //将dto对象转为TempKcjlDailyHy对象
            List<TempKcjlDailyHy> data = kcjl_hy.stream().map(f -> {
                TempKcjlDailyHy tempKcjlDailyHy = new TempKcjlDailyHy();
                BeanUtil.copyProperties(f, tempKcjlDailyHy);
                tempKcjlDailyHy.setHy(f.getHthm());
                return tempKcjlDailyHy;
            }).collect(Collectors.toList());

            // 插入数据到数据库
            insertSql(data);

			// 修改执行状态
			commonService.UpdateOrInsertStatus(dailyAuditStatus, name, currentDate);

			log.info("KcjlHy执行完毕");
        } catch (Exception e) {
            log.error("KcjlHy执行失败", e);
        }

    }

    // 处理belongs字段
    private TempKcjlDailyHyDTO alterbelongs(TempKcjlDailyHyDTO record) {
        if ("FDS".equals(record.getBelongs())) {
            record.setBelongs("FDS-" + ckCountryDict.getOrDefault(record.getPlace(), ""));
        } else if ("COSTWAY".equals(record.getBelongs())) {
            record.setBelongs("COSTWAY-" + ckCountryDict.getOrDefault(record.getPlace(), ""));
        }
        return record;
    }

    // 聚合相同记录
    private List<TempKcjlDailyHyDTO> aggregateRecords(List<TempKcjlDailyHyDTO> records) {
        Map<String, TempKcjlDailyHyDTO> aggregatedMap = new HashMap<>();

        for (TempKcjlDailyHyDTO record : records) {
            String key = record.getCpbh() + "_" + record.getPlace() + "_" + record.getBelongs() + "_" + record.getDate();
            if (aggregatedMap.containsKey(key)) {
                TempKcjlDailyHyDTO existingRecord = aggregatedMap.get(key);
                existingRecord.setSl(existingRecord.getSl() + record.getSl());
            } else {
                aggregatedMap.put(key, record);
            }
        }

        return new ArrayList<>(aggregatedMap.values());
    }

    // 获取进仓历史记录
    private List<TempKcjlDailyHyDTO> getJcjlHis() {

        //查询+去重
        List<TempKcjlDailyHyDTO> jcjlhis = jcjlHistoryMapper.getJcjlHistory()
                .stream()
                .distinct()
                .collect(Collectors.toList());


        // 处理异常belongs
        jcjlhis.forEach(dto -> {
            String belongs = dto.getBelongs();
            String hthm = dto.getHthm();
            String htrq = dto.getHtrq();
            if (StrUtil.isBlank(belongs) && ABNORMAL_BELONGS.containsKey(hthm)) {
                dto.setBelongs(ABNORMAL_BELONGS.get(hthm));
            }

            // 处理日期在2019-08-28之前的记录
            try {
                if (StrUtil.isNotBlank(htrq) && DATE_FORMAT.parse(htrq).before(DATE_FORMAT.parse("2019-08-28"))) {
                    dto.setBelongs("FDS-DE");
                }
            } catch (ParseException e) {
                log.error("解析日期失败: {},解析对象为{}", htrq, dto, e);
            }
        });


        // 过滤belongs为空的记录
        jcjlhis = jcjlhis.stream()
                .filter(dto -> dto.getBelongs() != null)
                .collect(Collectors.toList());

        // 处理place映射
        jcjlhis.forEach(dto -> {
            String place = dto.getPlace();
            if (place != null && VIRTUAL_CK.containsKey(place)) {
                dto.setPlace(VIRTUAL_CK.get(place));
            }
        });

        // 过滤restockPlaceList中的place
        jcjlhis = jcjlhis.stream()
                .filter(dto -> !RESTOCK_PLACE_LIST.containsKey(dto.getPlace()))
                .collect(Collectors.toList());

        return jcjlhis;
    }

    // 处理进仓记录
    private List<TempKcjlDailyHyDTO> addjcjl(List<TempKcjlDailyHyDTO> jcjldata, List<TempKcjlDailyHyDTO> kcjl_hy) {
        for (TempKcjlDailyHyDTO record : jcjldata) {
            boolean found = false;
            for (TempKcjlDailyHyDTO kcRecord : kcjl_hy) {
                if (kcRecord.getCpbh().equals(record.getCpbh()) &&
                        kcRecord.getPlace().equals(record.getPlace()) &&
                        kcRecord.getBelongs().equals(record.getBelongs()) &&
                        kcRecord.getHtrq().equals(record.getDate()) &&
                        kcRecord.getHthm().equals(record.getHthm())) {
                    kcRecord.setSl(kcRecord.getSl() + record.getSl());
                    found = true;
                    break;
                }
            }
            if (!found) {
                TempKcjlDailyHyDTO hyDTO = new TempKcjlDailyHyDTO();
                hyDTO.setCpbh(record.getCpbh());
                hyDTO.setPlace(record.getPlace());
                hyDTO.setSl(record.getSl());
                hyDTO.setBelongs(record.getBelongs());
                hyDTO.setHthm(record.getHthm());
                hyDTO.setHtrq(record.getDate());
                kcjl_hy.add(hyDTO);
            }
        }
        return kcjl_hy;
    }

    // 处理盘亏盘盈记录
    private List<TempKcjlDailyHyDTO> addpkpy(List<TempKcjlDailyHyDTO> pkpydata, List<TempKcjlDailyHyDTO> kcjl_hy, List<TempKcjlDailyHyDTO> jcjl_last) {
        if (pkpydata.isEmpty()) {
            return kcjl_hy;
        }

        for (TempKcjlDailyHyDTO record : pkpydata) {
            String cpbh = record.getCpbh();
            String place = record.getPlace();
            String belongs = record.getBelongs();
            int sl = record.getSl() == null ? 0 : record.getSl();

            // 排除特定的cpbh
            if (Arrays.asList("HW59104", "KC49465", "HW64114GR", "HW63759WH").contains(cpbh)) {
                continue;
            }

            // 查找当前库存
            List<TempKcjlDailyHyDTO> matchingRecords = kcjl_hy.stream()
                    .filter(kc -> kc.getCpbh().equals(cpbh) &&
                            kc.getPlace().equals(place) &&
                            kc.getBelongs().equals(belongs))
                    .collect(Collectors.toList());

            if (!matchingRecords.isEmpty()) {
                if (matchingRecords.size() > 1) {
                    // 检查是否有相同的htrq
                    Map<String, List<TempKcjlDailyHyDTO>> groupedByHtrq = matchingRecords.stream()
                            .collect(Collectors.groupingBy(TempKcjlDailyHyDTO::getHtrq));

                    if (groupedByHtrq.size() == 1 || hasMultipleGroupsWithSizeGreaterThanOne(groupedByHtrq)) {
                        // 逐个扣减
                        for (TempKcjlDailyHyDTO kc : matchingRecords) {
                            if (kc.getSl() - sl >= 0) {
                                kc.setSl(kc.getSl() - sl);
                                break;
                            } else {
                                sl = sl - kc.getSl();
                                kc.setSl(0);
                            }
                        }
                    } else {
                        // 日期不同，取最新日期的记录扣减
                        String lastdate = matchingRecords.stream()
                                .map(TempKcjlDailyHyDTO::getHtrq)
                                .max(Comparator.naturalOrder())
                                .orElse(null);

                        for (TempKcjlDailyHyDTO kc : matchingRecords) {
                            if (kc.getHtrq().equals(lastdate)) {
                                kc.setSl(kc.getSl() - sl);
                                break;
                            }
                        }
                    }
                } else {
                    // 只有一条记录，直接扣减
                    matchingRecords.get(0).setSl(matchingRecords.get(0).getSl() - sl);
                }
            } else {
                // 期初无库存，从历史记录中查找
                TempKcjlDailyHyDTO historyRecord = findHistoryRecordForCpbhAndBelongs(cpbh, belongs, jcjl_last);
                String hthm = historyRecord != null ? historyRecord.getHthm() : "";
                String htrq = historyRecord != null ? historyRecord.getDate() : "";

                // 添加负库存记录
                TempKcjlDailyHyDTO newRecord = new TempKcjlDailyHyDTO();
                newRecord.setCpbh(cpbh);
                newRecord.setPlace(place);
                newRecord.setSl(-sl);
                newRecord.setBelongs(belongs);
                newRecord.setHthm(hthm);
                newRecord.setHtrq(htrq);
                kcjl_hy.add(newRecord);
            }

        }

        return kcjl_hy;
    }

    // 检查是否有多个分组的大小大于1
    private boolean hasMultipleGroupsWithSizeGreaterThanOne(Map<String, List<TempKcjlDailyHyDTO>> groupedByHtrq) {
        long count = groupedByHtrq.values().stream()
                .filter(list -> list.size() > 1)
                .count();
        return count > 1;
    }

    // 查找指定cpbh和belongs的历史记录
    private TempKcjlDailyHyDTO findHistoryRecordForCpbhAndBelongs(String cpbh, String belongs, List<TempKcjlDailyHyDTO> jcjl_last) {
        if (belongs != null && belongs.contains("-")) {
            String belongsPrefix = belongs.split("-")[0];
            List<TempKcjlDailyHyDTO> matchingRecords = jcjl_last.stream()
                    .filter(kc -> kc.getCpbh().equals(cpbh) &&
                            kc.getBelongs() != null &&
                            kc.getBelongs().contains(belongsPrefix))
                    .collect(Collectors.toList());
            if (!matchingRecords.isEmpty()) {
                return matchingRecords.get(0);
            }
        }

        // 如果没有找到，尝试只匹配cpbh
        return jcjl_last.stream()
                .filter(kc -> kc.getCpbh().equals(cpbh))
                .findFirst()
                .orElse(null);
    }

    // 处理退货记录
    private List<TempKcjlDailyHyDTO> addthjl(List<TempKcjlDailyHyDTO> thjldata, List<TempKcjlDailyHyDTO> kcjl_hy, List<TempKcjlDailyHyDTO> jcjl_last) {
        for (TempKcjlDailyHyDTO record : thjldata) {

            String cpbh = record.getCpbh();
            String place = record.getPlace();
            String belongs = record.getBelongs();
            int sl = record.getSl() == null ? 0 : record.getSl();

            // 查找历史记录
            TempKcjlDailyHyDTO historyRecord = findHistoryRecordForCpbhAndBelongs(cpbh, belongs, jcjl_last);

            if (historyRecord != null) {
                String hthm = historyRecord.getHthm();
                String htrq = historyRecord.getDate();

                // 查找是否已存在相同记录
                boolean found = false;
                for (TempKcjlDailyHyDTO kcRecord : kcjl_hy) {
                    if (kcRecord.getCpbh().equals(cpbh) &&
                            kcRecord.getPlace().equals(place) &&
                            kcRecord.getBelongs().equals(belongs) &&
                            kcRecord.getHthm().equals(hthm)) {
                        kcRecord.setSl(kcRecord.getSl() + sl);
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    TempKcjlDailyHyDTO newRecord = new TempKcjlDailyHyDTO();
                    newRecord.setCpbh(cpbh);
                    newRecord.setPlace(place);
                    newRecord.setSl(sl);
                    newRecord.setBelongs(belongs);
                    newRecord.setHthm(hthm);
                    newRecord.setHtrq(htrq);
                    kcjl_hy.add(newRecord);
                }
            }else{
                // 如果没有找到，实际上会报异常
                log.error("未找到历史记录，请检查异常数据{}",record);
                throw new RuntimeException("未找到历史记录，请检查异常数据");
            }
        }

        return kcjl_hy;
    }

    // 处理转运记录
    private List<TempKcjlDailyHyDTO> addzyjl(List<TempKcjlDailyHyDTO> zyjldata, List<TempKcjlDailyHyDTO> kcjl_hy) {
        if (zyjldata.isEmpty()) {
            return kcjl_hy;
        }

        // 创建任务列表副本，以便在处理过程中移除已处理的任务
        List<TempKcjlDailyHyDTO> tasks = new ArrayList<>(zyjldata);

        // 按cpbh分组
        Map<String, List<TempKcjlDailyHyDTO>> cpbhGroups = tasks.stream()
                .collect(Collectors.groupingBy(TempKcjlDailyHyDTO::getCpbh));

        // 对每组任务进行排序
        List<TempKcjlDailyHyDTO> sortedTasks = new ArrayList<>();
        for (Map.Entry<String, List<TempKcjlDailyHyDTO>> entry : cpbhGroups.entrySet()) {
            List<TempKcjlDailyHyDTO> group = entry.getValue();
            if (group.size() == 1) {
                sortedTasks.addAll(group);
                continue;
            }

            // 计算每个zlck在zcck中出现的次数
            Map<String, Map<String, Long>> zcckCounter = new HashMap<>();
            for (TempKcjlDailyHyDTO task : group) {
                String zcck = task.getZcck();
                String zlck = task.getZlck();
                zcckCounter.computeIfAbsent(zlck, k -> new HashMap<>());
                zcckCounter.get(zlck).merge(zcck, 1L, Long::sum);
            }

            // 按照zcck出现次数和原始顺序排序
            List<TempKcjlDailyHyDTO> sortedGroup = group.stream()
                    .sorted((task1, task2) -> {
                        long count1 = zcckCounter.getOrDefault(task1.getZlck(), new HashMap<>())
                                .getOrDefault(task1.getZcck(), 0L);
                        long count2 = zcckCounter.getOrDefault(task2.getZlck(), new HashMap<>())
                                .getOrDefault(task2.getZcck(), 0L);
                        // 按照出现次数降序排列，如果次数相同则保持原始顺序
                        int result = Long.compare(count2, count1);
                        if (result == 0) {
                            // 保持原始顺序
                            return Integer.compare(group.indexOf(task1), group.indexOf(task2));
                        }
                        return result;
                    })
                    .collect(Collectors.toList());

            sortedTasks.addAll(sortedGroup);
        }

        // 使用while循环处理任务，并在处理完成后移除任务
        int i = 0;
        while (i < sortedTasks.size()) {
            TempKcjlDailyHyDTO task = sortedTasks.get(i);
            String cpbh = task.getCpbh();
            String zcck = task.getZcck();
            String zlck = task.getZlck();
            String frombelongs = task.getFrombelongs();
            String tobelongs = task.getTobelongs();
            int sl = task.getSl();

            // 查找转出仓库的库存
            List<TempKcjlDailyHyDTO> zcckKc = kcjl_hy.stream()
                    .filter(kc -> kc.getPlace().equals(zcck) &&
                            kc.getCpbh().equals(cpbh) &&
                            kc.getBelongs().equals(frombelongs))
                    .collect(Collectors.toList());

            if (zcckKc.isEmpty()) {
                i++;
                continue;
            }

            // 检查库存是否足够
            int totalSl = zcckKc.stream().mapToInt(TempKcjlDailyHyDTO::getSl).sum();
            if (totalSl < sl) {
                i++;
                continue;
            }

            // 按htrq排序，处理可能为null的情况
            zcckKc.sort(Comparator.comparing(TempKcjlDailyHyDTO::getHtrq,
                    Comparator.nullsLast(Comparator.naturalOrder())));

            int remainingSl = sl;
            for (TempKcjlDailyHyDTO kc : zcckKc) {
                if (remainingSl <= 0) {
                    break;
                }

                String hy = kc.getHthm();
                String htrq = kc.getHtrq();
                int kcsl = kc.getSl();

                if (kcsl >= remainingSl) {
                    // 扣减库存
                    kc.setSl(kcsl - remainingSl);
                    // 添加到转入仓库
                    addToTargetWarehouse(kcjl_hy, cpbh, zlck, tobelongs, remainingSl, hy, htrq);
                    remainingSl = 0;
                } else {
                    // 扣减全部库存
                    kc.setSl(0);
                    // 添加到转入仓库
                    addToTargetWarehouse(kcjl_hy, cpbh, zlck, tobelongs, kcsl, hy, htrq);
                    remainingSl -= kcsl;
                }
            }

            // 处理完成后从列表中移除该任务
            sortedTasks.remove(i);
        }

        return kcjl_hy;
    }

    // 添加到目标仓库
    private void addToTargetWarehouse(List<TempKcjlDailyHyDTO> kcjl_hy, String cpbh, String zlck, String tobelongs, int sl, String hy, String htrq) {
        boolean found = false;
        for (TempKcjlDailyHyDTO kcRecord : kcjl_hy) {
            if (kcRecord.getCpbh().equals(cpbh) &&
                    kcRecord.getPlace().equals(zlck) &&
                    kcRecord.getBelongs().equals(tobelongs) &&
                    kcRecord.getHthm().equals(hy)) {
                kcRecord.setSl(kcRecord.getSl() + sl);
                found = true;
                break;
            }
        }

        if (!found) {
            TempKcjlDailyHyDTO newRecord = new TempKcjlDailyHyDTO();
            newRecord.setCpbh(cpbh);
            newRecord.setPlace(zlck);
            newRecord.setSl(sl);
            newRecord.setBelongs(tobelongs);
            newRecord.setHthm(hy);
            newRecord.setHtrq(htrq);
            kcjl_hy.add(newRecord);
        }
    }

    // 处理销售记录
    private List<TempKcjlDailyHyDTO> addxsjl(List<TempKcjlDailyHyDTO> xsjldata, List<TempKcjlDailyHyDTO> kcjl_hy) {
        for (TempKcjlDailyHyDTO record : xsjldata) {
            String cpbh = record.getCpbh();
            String belongs = record.getBelongs();
            String place = record.getPlace();
            int sl = record.getSl() == null ? 0 : record.getSl();

            // 查找匹配的库存记录，按cpbh、belongs、place过滤 - 首先按照htrq进行排序 相同时 则在按照hthm的中间6位数字进行排序，拿最小的值
            List<TempKcjlDailyHyDTO> matchingRecords = kcjl_hy.stream()
                    .filter(kc -> kc.getCpbh().equals(cpbh) &&
                            kc.getBelongs().equals(belongs) &&
                            kc.getPlace().equals(place))
                    .sorted(Comparator.comparing(TempKcjlDailyHyDTO::getHtrq,
                            Comparator.nullsLast(Comparator.naturalOrder())).
							thenComparing(f->f.getHthm().split("-", 2)[1].substring(0, 6)))
                    .collect(Collectors.toList());

            int remainingSl = sl;
            for (TempKcjlDailyHyDTO kc : matchingRecords) {
                if (remainingSl <= 0) {
                    break;
                }

                int kcsl = kc.getSl();
                if (kcsl >= remainingSl) {
                    kc.setSl(kcsl - remainingSl);
                    remainingSl = 0;
                } else {
                    kc.setSl(0);
                    remainingSl -= kcsl;
                }
            }
        }

        return kcjl_hy;
    }

    // 获取最后进仓历史记录
    private List<TempKcjlDailyHyDTO> getLastJcjlhis(List<TempKcjlDailyHyDTO> jcjlhis, String date) {
        try {
            Date cutoffDate = DATE_FORMAT.parse(date);

            // 过滤日期小于指定日期的记录
            List<TempKcjlDailyHyDTO> newjcjlhis = jcjlhis.stream()
                    .filter(dto -> {
                        try {
                            Date recordDate = DATE_FORMAT.parse(dto.getHtrq());
                            return recordDate.before(cutoffDate);
                        } catch (ParseException e) {
                            return false;
                        }
                    })
                    .collect(Collectors.toList());

            // 处理newBelongs值
            newjcjlhis.forEach(f -> {
                // 提取belongs第一部分
                String belongs = f.getBelongs();
                if (belongs.contains("-")) {
                    f.setNewBelongs(belongs.split("-")[0]);
                } else {
                    f.setNewBelongs("null");
                }
            });

            // 重要（可能会造成与月审计异常的原因）：按htrq排序 htrq一致时，按照hthm（PLLT-250426QD）的中间6位数字排序，数字按降序排，取最小数字的那个仓库
            newjcjlhis.sort(Comparator.comparing(TempKcjlDailyHyDTO::getHtrq,
                    Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(
                    (TempKcjlDailyHyDTO dto1, TempKcjlDailyHyDTO dto2) -> {
                        // 提取hthm中间的6位数字
                        int num1 = extractMiddleSixDigits(dto1.getHthm());
                        int num2 = extractMiddleSixDigits(dto2.getHthm());

                        // 按照数字降序排序（较大的数字排在前面）
                        return Integer.compare(num2, num1);
                    }
            ));

            // 去重，保留最新的记录
            Map<String, TempKcjlDailyHyDTO> uniqueRecords = new LinkedHashMap<>();
            for (TempKcjlDailyHyDTO dto : newjcjlhis) {
                String key = dto.getCpbh() + "_" + dto.getNewBelongs();
                uniqueRecords.put(key, dto);
            }

            List<TempKcjlDailyHyDTO> result = new ArrayList<>(uniqueRecords.values());
            result = result.stream().map(f -> {
                TempKcjlDailyHyDTO hyDTO = new TempKcjlDailyHyDTO();
                hyDTO.setCpbh(f.getCpbh());
                hyDTO.setBelongs(f.getNewBelongs());
                hyDTO.setHthm(f.getHthm());
                hyDTO.setDate(f.getHtrq());
                return hyDTO;
            }).collect(Collectors.toList());

            return result;
        } catch (ParseException e) {
            log.error("解析日期失败: {}", date, e);
            return new ArrayList<>();
        }
    }

    /**
     * 提取合同号中间的6位数字
     * 例如：PLLT-250426QD -> 250426
     * @param hthm 合同号
     * @return 中间的6位数字，如果无法提取则返回0
     */
    private int extractMiddleSixDigits(String hthm) {
        if (hthm == null || hthm.isEmpty()) {
            return 0;
        }

        try {
            String[] parts = hthm.split("-");
            if (parts.length < 2 || parts[1].length() < 6) {
                return 0;
            }

            String numberPart = parts[1].substring(0, 6);
            return Integer.parseInt(numberPart);
        } catch (NumberFormatException | StringIndexOutOfBoundsException e) {
            return 0;
        }
    }

    // 按顺序处理各种数据
    private List<TempKcjlDailyHyDTO> getFinalData(List<TempKcjlDailyHyDTO> jcjldata, List<TempKcjlDailyHyDTO> pkpydata,
                                                  List<TempKcjlDailyHyDTO> thjldata, List<TempKcjlDailyHyDTO> xsjldata,
                                                  List<TempKcjlDailyHyDTO> zyjldata, List<TempKcjlDailyHyDTO> jcjl_last,
                                                  List<TempKcjlDailyHyDTO> kcjl_hy) {
        // 逻辑顺序 jcjldata>pkpydata>thjldata>zyjldata>xsjldata
        kcjl_hy = addjcjl(jcjldata, kcjl_hy); // 校验成功
        kcjl_hy = addpkpy(pkpydata, kcjl_hy, jcjl_last); // 校验成功
        kcjl_hy = addthjl(thjldata, kcjl_hy, jcjl_last); // 校验成功
        kcjl_hy = addzyjl(zyjldata, kcjl_hy); // 校验成功
        kcjl_hy = addxsjl(xsjldata, kcjl_hy); // 校验成功
        return kcjl_hy;
    }

    // 插入数据到数据库
    private void insertSql(List<TempKcjlDailyHy> data) {
        try {
            tempKcjlDailyHyMapper.batchInsert(data);
            log.info("插入数据成功，kcjl_hy的数量为：{}", data.size());
        } catch (Exception e) {
            log.error("插入数据失败", e);
        }
    }


}
